package com.wise.common.base.repository.impl;

import com.wise.common.base.repository.BaseRepository;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaEntityInformationSupport;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.lang.reflect.ParameterizedType;

//@Repository("baseRepository")
public abstract class BaseRepositoryImpl<T, ID extends Long>
        //extends SimpleJpaRepository<T, ID>
        implements BaseRepository<T, ID> {

    @PersistenceContext
    protected EntityManager em;

    //private final JpaEntityInformation<T, ?> entityInformation;

    private Class<T> entityClass;

    /*
    public BaseRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
        //super(entityInformation,entityManager);
        this.entityInformation = entityInformation;
        this.em = entityManager;

        // 获取泛型的实际类型
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        entityClass = (Class<T>)type.getActualTypeArguments()[0];
    }

    public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
        this(JpaEntityInformationSupport.getEntityInformation(domainClass, em), em);
    }
    */

    @SuppressWarnings("unchecked")
    public BaseRepositoryImpl(){
        /**
         * 获取泛型的实际类型
         */
        ParameterizedType type =	(ParameterizedType) this.getClass().getGenericSuperclass();
        entityClass = (Class<T>)type.getActualTypeArguments()[0];

    }


    @Override
    public void deleteObject(T obj) {
        // TODO Auto-generated method stub
        em.remove(em.merge(obj));
    }

    @Override
    public T findObject(ID id) {
        // TODO Auto-generated method stub
        return (T)em.find(entityClass,id);
    }

    @Override
    public void saveOrUp(T t){
        em.merge(t);
    }

    @Override
    public void saveObject(T obj) {
        // TODO Auto-generated method stub
        em.persist(obj);
    }

    @Override
    public void updateObject(T obj) {
        // TODO Auto-generated method stub
        em.merge(obj);
    }
}
